package com.shan.common.base;

import com.shan.common.util.PropertiesFileUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.InvalidSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: shanzheng <br/>
 * Description: 控制器基类<br/>
 * Date： 17:41 2017/8/5.<br/>
 * Modified By: <br/>
 */
public class BaseController {

    private final static Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * Description: 统一异常处理<br/>
     * Param: [request, response, exception] <br/>
     * Author:shanzheng <br/>
     * Date: 17:49 2017/8/5 <br/>
     * Return: java.lang.String <br/>
     */
    public String exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception exception){
        logger.error("统一异常处理",exception);
        request.setAttribute("ex",exception);
        if(request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")){
            request.setAttribute("requestHeader","ajax");
        }
        //shiro没有权限异常
        if(exception instanceof UnauthorizedException){
            return "";//返回到指定的地方
        }
        // shiro会话已过期异常
        if(exception instanceof InvalidSessionException){
            return "error.jsp";
        }
        return "/error.jsp";
    }

    /**
     * Description: 返回jsp视图<br/>
     * Param: [path：路径 ] <br/>
     * Author: shanzheng <br/>
     * Date: 9:37 2017/8/7 <br/>
     * Return: java.lang.String <br/>
     */
    public static String jsp(String path) {
        return path.concat(".jsp");
    }


    /**
     * Description: 返回thymeleaf视图<br/>
     * Param: [path:路径] <br/>
     * Author:shanzheng <br/>
     * Date: 9:38 2017/8/7 <br/>
     * Return: java.lang.String <br/>
     */
    public static String thymeleaf(String path) {
        String folder = PropertiesFileUtil.getInstance().get("app.name");
        return "/".concat(folder).concat(path).concat(".html");
    }
}
